<?php
/**
 * jishupu-cms
 * @Author:技术铺
 * @Date:2021/11/21
 */

namespace App\Filters;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

/**
 * 模型全局过滤器基类
 * 应用场景：主要用于列表数据条件筛选
 *
 * Class BaseFilter
 * @package App\Filters
 */
class BaseFilter
{
    protected $builder;
    protected $filters;

    /**
     * @param Builder $builder
     * @return Builder
     */
    public function apply(Builder $builder)
    {
        $this->builder = $builder;
        $this->filters = \request()->all();
        if (filled($this->filters)) {
            foreach ($this->filters as $name => $value) {
                // 蛇形参数转小驼峰：keywords_key => keywordsKey
                $name = Str::camel($name);
                if (method_exists($this, $name)) {
                    call_user_func_array([$this, $name], [$value]);
                }
            }
        }
        return $this->builder;
    }

    /**
     * 通用：关键词组合搜索条件
     * @param $keywords_key
     */
    protected function keywordsKey($keywords_key)
    {
        if (filled($this->filters['keywords_value'])) {
            if (filled($keywords_key)) {
                return $this->builder->where($keywords_key, 'like', '%' . $this->filters['keywords_value'] . '%');
            } else {
                return $this->builder->where('id', -1);
            }
        }
    }

    /**
     * 通用：状态条件
     * @param $status
     * @return mixed
     */
    protected function status($status)
    {
        if (filled($status)) return $this->builder->where('status', $status);
    }

    /**
     * 通用：排序
     * @param $sort
     * @return mixed
     */
    protected function sort($sort)
    {
        if (filled($sort)) {
            preg_match('/(\-|\+)(.*)/', $sort, $sort_result);
            if (filled($sort_result[2]) && filled($sort_result[1])) {
                $this->builder->orderBy($sort_result[2], $sort_result[1] == '-' ? 'desc' : 'asc');
                if ($sort_result[2] != 'id') {
                    $this->builder->orderBy('id', 'desc');
                }
                return $this->builder;
            }
        }
        return $this->builder->orderBy('id', 'desc');
    }

}
